package main

import (
    "encoding/json"
    `errors`
    "fmt"
    `gowebprog/ch02/chitchat/data`
    `strings`

    "html/template"
    "log"
    "net/http"
    "os"
)

// 实现printing到标准输出
func p(a ...interface{}) {
    fmt.Println(a)
}

// version
func version() string {
    return "0.1"
}

// 配置文件数据结构
type Configuration struct {
    Address      string
    ReadTimeout  int64
    WriteTimeout int64
    Static       string
}

// 全局变量
var (
    config Configuration
    logger *log.Logger
)

// 加载配置文件函数
func loadConfig() {
    file, err := os.Open("config.json")
    if err != nil {
        log.Fatalln("打开文件失败", err)
    }
    defer file.Close()
    decoder := json.NewDecoder(file)
    config = Configuration{}
    err = decoder.Decode(&config)

    if err != nil {
        log.Fatalln("配置文件格式错误", err)
    }

}

// parse HTML templates
// pass in a list of file names, and get a template
func parseTemplateFiles(filenames ...string) (t *template.Template) {
    var files []string
    t = template.New("layout")
    for _, file := range filenames {
        files = append(files, fmt.Sprintf("templates/%s.html", file))
    }
    t = template.Must(t.ParseFiles(files...))
    return // 返回模板列表
}

//  最通用的模板渲染
func generateHTML(w http.ResponseWriter, data interface{}, filenames ...string) {
    var files []string
    for _, file := range filenames {
        files = append(files, fmt.Sprintf("templates/%s.html", file))
    }
    templates := template.Must(template.ParseFiles(files...))
    templates.ExecuteTemplate(w, "layout", data)
}

// 写日志方法
func info(args ...interface{}) {
    logger.SetPrefix("INFO ")
    logger.Println(args...)
}

func danger(args ...interface{}) {
    logger.SetPrefix("ERROR ")
    logger.Println(args...)
}

func warning(args ...interface{}) {
    logger.SetPrefix("WARNING ")
    logger.Println(args...)
}

// 初始化函数
func init() {
    loadConfig()
    file, err := os.OpenFile("chitchat.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalln("打开日志文件失败", err)
    }
    // 实现日志写入文件
    logger = log.New(file, "INFO ", log.Ldate|log.Ltime|log.Lshortfile)
}

// 检查用户是否已经登录, 如果登录则带有session
func session(w http.ResponseWriter, r *http.Request) (sess data.Session, err error) {
    cookie, err := r.Cookie("_cookie")
    if err == nil {
        sess = data.Session{Uuid: cookie.Value}
        if ok, _ := sess.Check(); !ok {
            err = errors.New("Invalid session " + cookie.Value)
        }

    }

    return
}

func error_message(w http.ResponseWriter, r *http.Request, msg string) {
    url := []string{"/err?msg=", msg}
    http.Redirect(w, r, strings.Join(url, ""), 302)
}
